package org.news.web.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.news.web.domain.Categories;
import org.news.web.domain.Creators;
import org.news.web.domain.Users;
import org.news.web.domain.vo.CreatorsVo;
import org.news.web.mapper.CategoriesMapper;
import org.news.web.mapper.CreatorsMapper;
import org.news.web.mapper.UsersMapper;
import org.news.web.service.ICategoriesService;
import org.news.web.service.ICreatorsService;
import org.springframework.stereotype.Service;
import org.news.web.domain.bo.SubscriptionsBo;
import org.news.web.domain.vo.SubscriptionsVo;
import org.news.web.domain.Subscriptions;
import org.news.web.mapper.SubscriptionsMapper;
import org.news.web.service.ISubscriptionsService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 订阅功能Service业务层处理
 *
 * @author Gu Ci
 * @date 2024-04-21
 */
@Transactional
@RequiredArgsConstructor
@Service
public class SubscriptionsServiceImpl implements ISubscriptionsService {

    private final SubscriptionsMapper baseMapper;

    private final CategoriesMapper categoriesMapper;

    private final ICategoriesService iCategoriesService;

    private final CreatorsMapper creatorsMapper;

    private final UsersMapper usersMapper;

    /**
     * 查询订阅功能
     */
    @Override
    public SubscriptionsVo queryById(Long subscriptionId){
        return baseMapper.selectVoById(subscriptionId);
    }

    /**
     * 查询订阅功能列表
     */
    @Override
    public TableDataInfo<SubscriptionsVo> queryPageList(SubscriptionsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Subscriptions> lqw = buildQueryWrapper(bo);
        Page<SubscriptionsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        /**
         * 获取用户名称 并且赋值
         */
        /**
         * 获取栏目或者作者名称
         */
        if(ObjectUtil.isNotNull(result.getRecords()) && result.getRecords().size() > 0){
            List<Long> ids = result.getRecords().stream().map(SubscriptionsVo::getSubscriberId).collect(Collectors.toList());
            List<Long> Lms = result.getRecords().stream().filter(item ->{return item.getStatus() == 1;}).map(SubscriptionsVo::getTargetCategoryId).collect(Collectors.toList());
//           获取订阅者的用户信息
            List<Users> userinfos = usersMapper.selectList(new QueryWrapper<Users>().in("user_id", ids));
            if(Lms != null && Lms.size()> 0){
//                设置栏目的name信息
                List<Categories> LmInfos = categoriesMapper.selectList(new QueryWrapper<Categories>().in("category_id", Lms));
                System.out.println("LmInfos ==>"+LmInfos);
                result.getRecords().forEach((item)->{
                    LmInfos.stream().forEach((lm)->{
                        if(lm.getCategoryId().longValue() == item.getTargetCategoryId().longValue()){
                            item.setAuthor(lm.getCategoryName());
                        }
                    });
                });
            }
//           获取作者信息
            List<Long> Crs = result.getRecords().stream().filter(item ->{return item.getStatus() == 2;}).map(SubscriptionsVo::getTargetCategoryId).collect(Collectors.toList());
            if(Crs != null && Crs.size()> 0){
                List<CreatorsVo> CrsInfos = creatorsMapper.selectVoList(new LambdaQueryWrapper<Creators>().in(Creators::getCreatorId, Crs));
                System.out.println("CrsInfos ==>"+CrsInfos);
                Set<Long> collect = CrsInfos.stream().map(CreatorsVo::getUserId).collect(Collectors.toSet());
                if(collect.size() != 0){
                    List<Users> usersList = usersMapper.selectList(new QueryWrapper<Users>().in("user_id", collect));


                    usersList.forEach(users -> {
                        CrsInfos.forEach(crs ->{
                            if(crs.getUserId() == users.getUserId()){
                                crs.setUsername(users.getUsername());
                            }
                        });
                    });
                    result.getRecords().forEach((item)->{
                        CrsInfos.stream().forEach((crs)->{
                            if(crs.getCreatorId().longValue() == item.getTargetCategoryId().longValue()){
                                item.setAuthor(crs.getUsername());
                            }
                        });
                    });
                }

            }

            result.getRecords().forEach((item)->{
                userinfos.stream().forEach((user)->{
                    if(user.getUserId().longValue() == item.getSubscriberId().longValue()){
                        item.setUsername(user.getUsername());
                    }
                });
            });

        }

        return TableDataInfo.build(result);
    }

    /**
     * 查询订阅功能列表
     */
    @Override
    public List<SubscriptionsVo> queryList(SubscriptionsBo bo) {
        LambdaQueryWrapper<Subscriptions> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Subscriptions> buildQueryWrapper(SubscriptionsBo bo) {
        LambdaQueryWrapper<Subscriptions> lqw = Wrappers.lambdaQuery();
        if(bo.getSubscriberId() == null){
            //       获取模糊查询的用户
            Set<Long> userIds = null;
            if(StringUtils.isNotBlank(bo.getUsername())){
                List<Users> username = usersMapper.selectList(new QueryWrapper<Users>().like("username", bo.getUsername()));
                if(ObjectUtil.isNotNull(username) && username.size() >0){
                    userIds = username.stream().map(Users::getUserId).collect(Collectors.toSet());
                }else{
//                查询不到用户 给一个查不到的id
                    userIds = new HashSet<>();
                    userIds.add(-1l);
                }
            }
            lqw.in(userIds!= null, Subscriptions::getSubscriberId, userIds);
        }else{
            lqw.eq(bo.getSubscriberId()!= null, Subscriptions::getSubscriberId, bo.getSubscriberId());
        }

        lqw.eq(bo.getStatus() != null, Subscriptions::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增订阅功能
     */
    @Override
    public Boolean insertByBo(SubscriptionsBo bo) {
        Subscriptions subscriptions = baseMapper.selectOne(new LambdaQueryWrapper<Subscriptions>().eq(Subscriptions::getStatus, bo.getStatus()).eq(Subscriptions::getTargetCategoryId, bo.getTargetCategoryId()).eq(Subscriptions::getSubscriberId, bo.getSubscriberId()));
        System.out.println(subscriptions);
        if(subscriptions != null){
            throw new ServiceException("该订阅以存在 无法创建!");
        }
        Subscriptions add = MapstructUtils.convert(bo, Subscriptions.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
//        判断是否存在

        //        判断是栏目还是作者
        if(bo.getStatus() == 1){
            //栏目
            categoriesMapper.update(new LambdaUpdateWrapper<Categories>().eq(Categories::getCategoryId,bo.getTargetCategoryId()).setSql("subscriber_count=subscriber_count+1"));
        }else{
            //作者
            creatorsMapper.update(new LambdaUpdateWrapper<Creators>().eq(Creators::getCreatorId,bo.getTargetCategoryId()).setSql("followers_count=followers_count+1"));
        }
        if (flag) {
            bo.setSubscriptionId(add.getSubscriptionId());
        }
        return flag;
    }

    /**
     * 修改订阅功能
     */
    @Override
    public Boolean updateByBo(SubscriptionsBo bo) {
        Subscriptions update = MapstructUtils.convert(bo, Subscriptions.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Subscriptions entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除订阅功能
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(ids == null && ids.size() == 0){
            throw new ServiceException("出现故障!");
        }
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        List<SubscriptionsVo> subscriptionsVos = baseMapper.selectVoList(new LambdaQueryWrapper<Subscriptions>().in(Subscriptions::getSubscriptionId, ids));
        subscriptionsVos.forEach(item ->{
            if(item.getStatus() == 1){
                //栏目
                categoriesMapper.update(new LambdaUpdateWrapper<Categories>().eq(Categories::getCategoryId,item.getTargetCategoryId()).setSql("subscriber_count=subscriber_count-1"));
            }else{
                //作者
                creatorsMapper.update(new LambdaUpdateWrapper<Creators>().eq(Creators::getCreatorId,item.getTargetCategoryId()).setSql("followers_count=followers_count-1"));
            }
        });
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Boolean isSub(SubscriptionsBo subscriptionsBo) {

        Long count = baseMapper.selectCount(new LambdaQueryWrapper<Subscriptions>()
            .eq(Subscriptions::getStatus, subscriptionsBo.getStatus())
            .eq(Subscriptions::getTargetCategoryId, subscriptionsBo.getTargetCategoryId())
            .eq(Subscriptions::getSubscriberId, subscriptionsBo.getSubscriberId())
        );
        return count>0;
    }
}
